import Router from 'koa-router';
import { empty } from '#Utils/helper.js';

// 继承 koa-router 并添加 group 函数
export default class CustomRouter extends Router {
    group = (prefix = '', middleware = [], routes) => {
        const routeList = routes()
        if (empty(routeList)) {
            return;
        }

        const groupRouter = new CustomRouter();

        routeList.forEach((route) => {
            let [method, path, ...handers] = route;
            if (method === 'group') {
                let [subMiddleware, subRoutes] = handers;
                // 合并中间件
                subMiddleware = [...middleware, ...subMiddleware];

                groupRouter.group(path, subMiddleware, subRoutes);
            } else {
                groupRouter[method](path, ...middleware, ...handers)
            }
        })

        this.use(prefix, groupRouter.routes(), groupRouter.allowedMethods());
    }
}